<template>
    <div class="wrapper">
        <div class="dis" v-if="type==0">
            <div class="main">
                <div class="dia">
                    <div class="line">

                    </div>
                    <div class="basic">
                        认证信息
                    </div>
                </div>
                <div class="main_line">

                </div>
                <div class="">
                    <van-field v-model="agentIdCardName" label="姓名" placeholder="请输入姓名" :border="false" />
                    <van-field v-model="agentIdCardNo" label="身份证号" placeholder="请输入身份证号" :border="false" />
                </div>
                <div class="info">
                    <div class="form">
                        <div class="upload" @click="jurisdiction">
                            <div class="left">
                                <van-uploader :before-read="file => afterReadUploadImg(file, 'agentIdCardFront')">
                                    <img class="uploadImg"
                                        :src="agentIdCardFront ? agentIdCardFront : 'https://agent.mtpospay.com/cardz.png'"
                                        alt="" />
                                </van-uploader>


                                <div class="uploader_title">身份证人像照</div>
                            </div>
                            <div class="right">
                                <van-uploader :before-read="file => afterReadUploadImg(file, 'agentIdCardBack')">
                                    <img class="uploadImg"
                                        :src="agentIdCardBack ? agentIdCardBack : 'https://agent.mtpospay.com/cardf.png'"
                                        alt="" />
                                </van-uploader>
                                <div class="uploader_title">身份证国徽照</div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="dis" v-else>
            <div class="main">
                <div class="dia">
                    <div class="line">

                    </div>
                    <div class="basic">
                        客服信息
                    </div>
                </div>
                <div class="main_line">

                </div>
                <div class="">
                    <van-field v-model="serviceContent" label="客服提示语" placeholder="请输入客服提示语" :border="false" />
                </div>
                <div class="info">
                    <div class="form">
                        <div class="upload" @click="jurisdiction">
                            <div class="left">
                                <van-uploader :before-read="file => afterReadUploadImg(file, 'serviceQrCode')">
                                    <img class="uploadImg"
                                        :src="serviceQrCode ? serviceQrCode : 'http://mtpospay.com/camera.png'"
                                        alt="" />
                                </van-uploader>
                                <div class="uploader_title">客服二维码</div>
                            </div>
                            <!-- <div class="right">
                                <van-uploader :before-read="file => afterReadUploadImg(file, 'agentIdCardBack')">
                                    <img class="uploadImg"
                                        :src="agentIdCardBack ? agentIdCardBack : 'https://agent.mtpospay.com/cardf.png'"
                                        alt="" />
                                </van-uploader>
                                <div class="uploader_title">身份证国徽照</div>
                            </div> -->
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="btn_box">
            <div class="btn dis" @click="submit">
                提交
            </div>
        </div>
        <transition name="van-slide-down">
            <div class="pouple" v-if="visible">
                <div class="pouple_box">
                    <div class="specification">
                        相机，相册权限说明
                    </div>
                    <div class="pouple_font">
                        便于您使用该功能上传您的照片/图片及用于新增服务商场景中读取和写入相册和文件内容
                    </div>
                </div>
            </div>
        </transition>
    </div>
</template>

<script>
    import {
        agentReal,
        alOcr,
        updateAgentInf
    } from '@/api/terminal'
    import {
        host
    } from '@/constant'
    import store from '@/store'
    import ImageCompressor from 'image-compressor.js';
    import {
        showToast
    } from 'vant'
    import {
        useRoute,
        useRouter,
        RouterView
    } from 'vue-router'
    import axios from 'axios'
    import {
        defineComponent,
        reactive,
        toRefs,
        ref,
        onMounted
    } from 'vue';
    export default defineComponent({
        name: 'sateActive',
        setup() {
            const router = useRouter()
            const route = useRoute()
            const state = reactive({
                active: 0,
                loading: false,
                finished: false,
                currentPage: 1,
                checkedAll: false,
                checked: [],
                numAll: 0,
                posList: [],
                visible: false,
                type: 0,
                serviceQrCode: "",
                serviceContent: ""
            })
            state.type = route.query.type
            const information = reactive({
                agentIdCardName: "",
                agentIdCardNo: "",
                agentIdCardFront: "",
                agentIdCardBack: ""
            })
            const jurisdiction = () => {
                const permission = 'android.permission.READ_EXTERNAL_STORAGE' // 要检查的权限
                plus.android.checkPermission(
                    permission,
                    granted => {
                        // 0(已获取权限) -1未获取权限
                        if (granted.checkResult == -1) {
                            state.visible = true
                        } else if (granted.checkResult == 0) {
                            afterReadUploadImg()
                        }

                    },
                    error => {
                        console.error('Error checking permission:', error.message)
                    }
                )
                const permissionCAMERA = 'android.permission.CAMERA' // 要检查的权限
                plus.android.checkPermission(
                    permissionCAMERA,
                    granted => {
                        // 0(已获取权限) -1未获取权限
                        if (granted.checkResult == -1) {
                            state.visible = true
                        } else if (granted.checkResult == 0) {
                            state.visible = false
                        }

                    },
                    error => {
                        console.error('Error checking permission:', error.message)
                    }
                )
                plus.android.requestPermissions(['android.permission.READ_EXTERNAL_STORAGE',
                        'android.permission.CAMERA'
                    ],
                    (e) => {
                        //关闭
                        state.visible = false
                        if (e.granted.length > 0) {
                            //执行你有权限后的方法
                            console.log('afterReadUploadImg')
                            afterReadUploadImg()
                        }
                    })
            }
            //图片压缩
            const compressImage = (file) => {
                console.log(file)
                return new Promise((resolve, reject) => {
                    const options = {
                        success(result) {
                            // 将压缩后的 Blob 转换为 File 对象（如果组件支持Blob则不用这一步）
                            const compressedFile = new File([result], file.name, {
                                type: file.type,
                                lastModified: Date.now(),
                            });
                            return resolve(compressedFile);
                        },
                        error(e) {
                            return reject(e);
                        },
                    };
                    // 1-3MB
                    if (file.size > 1 * 1024 * 1024 && file.size <= 3 * 1024 * 1024) {
                        options.quality = 0.3; // 压缩质量
                        options.convertSize = false; //不进行图像尺寸的调整
                        options.checkOrientation = false; // 图片翻转，默认为false
                    }
                    // 3-4MB
                    if (file.size > 3 * 1024 * 1024 && file.size <= 4 * 1024 * 1024) {
                        options.quality = 0.25; // 压缩质量
                        options.convertSize = false; //不进行图像尺寸的调整
                        options.checkOrientation = false; // 图片翻转，默认为false
                    }
                    // 5-6MB
                    if (file.size > 5 * 1024 * 1024 && file.size <= 6 * 1024 * 1024) {
                        options.quality = 0.2; // 压缩质量
                        options.convertSize = false; //不进行图像尺寸的调整
                        options.checkOrientation = false; // 图片翻转，默认为false
                    }
                    // 6-7MB
                    if (file.size > 6 * 1024 * 1024 && file.size <= 7 * 1024 * 1024) {
                        options.quality = 0.15; // 压缩质量
                        options.convertSize = false; //不进行图像尺寸的调整
                        options.checkOrientation = false; // 图片翻转，默认为false
                    }
                    // 7-9MB
                    if (file.size > 7 * 1024 * 1024 && file.size <= 9 * 1024 * 1024) {
                        options.quality = 0.1; // 压缩质量
                        options.convertSize = false; //不进行图像尺寸的调整
                        options.checkOrientation = false; // 图片翻转，默认为false
                    }
                    new ImageCompressor(file, options);
                });
            }
            const afterReadUploadImg = async (file, key) => {
                console.log('asd',file, key)
                let stramFile = await compressImage(file)
                // store.state.
                console.log(stramFile)
                const formData = new FormData();
                formData.append('file', stramFile);
                store.dispatch('data/GetLoading', true)
                axios.post(host + '/file/addFile', formData, {
                        headers: {
                            'token': localStorage.getItem('token'),
                            'sysType': 'app',
                        }
                    })
                    .then(response => {
                        console.log('获取图片链接', response);
                        if (response.data.code == 999999) {
                            showToast(response.data.message)
                            store.dispatch('data/GetLoading', false)
                            return
                        }
                        store.dispatch('data/GetLoading', false)
                        if (key == 'agentIdCardFront' && response.data.data.url) {
                            information.agentIdCardFront = response.data.data.url
                            getOcr(response.data.data.url)
                        } else if (key == 'serviceQrCode') {
                            state.serviceQrCode = response.data.data.url
                        } else {
                            information.agentIdCardBack = response.data.data.url
                        }
                    })
                    .catch(error => {
                        console.error('报错', error);
                    });

            }

            const submit = () => {
                if (state.type == 0) {
                    if (!validateForm()) {
                        return
                    }
                    agentReal(information).then(res => {
                        showToast('修改成功')
                        setTimeout(() => {
                            router.go(-1)
                        }, 2000)
                    })
                } else {
                    if (state.serviceQrCode == '') {
                        showToast('请输入客服二维码图片')
                        return
                    }
                    if (state.serviceQrCode == '') {
                        showToast('请输入客服提示语')
                        return
                    }
                    let parames = {
                        serviceQrCode: state.serviceQrCode,
                        serviceContent: state.serviceContent,
                    }
                    updateAgentInf(parames).then(res => {
                        showToast('修改成功')
                        setTimeout(() => {
                            router.go(-1)
                        }, 2000)
                    })
                }

            }
            // 校验规则
            const validateForm = () => {
                if (!information.agentIdCardName) {
                    showToast('姓名不能为空')
                    return false;
                }

                if (!information.agentIdCardNo) {
                    showToast('身份证号不能为空')
                    return false;
                }

                if (!information.agentIdCardFront) {
                    showToast('身份证人像照不能为空')
                    return false;
                }

                if (!information.agentIdCardBack) {
                    showToast('身份证国徽照不能为空')
                    return false;
                }

                return true;
            };
            //ocr识别
            const getOcr = (e, item, file) => {
                let parames = {
                    imgUrl: e,
                    imgType: "0"
                }

                alOcr(parames).then(res => {
                    information.agentIdCardName = res.data.idCardName
                    information.agentIdCardNo = res.data.idCardNo
                }).catch(error => {
                    information.agentIdCardFront = ''
                })
            }
            // const getFindPageList = () => {
            //     findSetPosFeeList({
            //         currentPage: state.currentPage,
            //         ...state.childData
            //     }).then(res => {
            //         if (res.object.length < 10) {
            //             state.finished = true
            //             state.loading = false
            //         } else {
            //             state.currentPage++
            //             state.finished = false
            //             state.loading = false
            //         }
            //         state.posList = state.posList.concat(res.object)
            //     })
            // }

            return {
                ...toRefs(state),
                ...toRefs(information),
                jurisdiction,
                afterReadUploadImg,
                getOcr,
                submit,
                validateForm,
                compressImage
            }
        }
    })
</script>
<style scoped lang="scss">
    .wrapper {
        width: 100%;
        min-height: 100vh;
        height: 100%;
        background-color: #FFF9F9;

        .main {
            width: 92%;
            // height: 124px;
            background: #fff;
            padding: 13px 13px 11px 13px;
            box-sizing: border-box;
            margin-top: 12px;

            .line {
                width: 3px;
                height: 13px;
                background: #FF5A3D;
                border-radius: 2px;
            }

            .basic {
                font-family: PingFangSC, PingFang SC;
                font-weight: 500;
                font-size: 14px;
                color: #FF5A3D;
                margin-left: 8px;
            }

            .main_line {
                width: 100%;
                height: 1px;
                border-bottom: 1px solid #F3F3F3;
                margin-top: 13px;
            }

            .card {
                margin-top: 12px;
                font-family: PingFangSC, PingFang SC;
                font-weight: 500;
                font-size: 12px;
                color: #FF5A3D;

                img {
                    width: 133px;
                    height: 92px;
                }
            }

            .info {
                margin-top: 12px
            }

            .form {
                background: #fffffe;

                .uploader_title {
                    text-align: center;
                    padding: 10px;
                    font-size: 12px;
                    color: #FF5A3D;
                }

                .upload {
                    // padding: 10px;
                    display: flex;
                    justify-content: space-between;

                    .left {
                        position: relative;

                        .loading {
                            position: absolute;
                            left: 50%;
                            top: 50%;
                            transform: translate(-50%, -50%);
                        }
                    }

                    .uploadImg {
                        border-radius: 6px;
                        width: 150px;
                        height: 100px;
                    }
                }

                .infoMax {
                    padding: 0px 20px 10px 20px;
                }

                .info {
                    background: #ffffff;
                    box-shadow: 0px 0px 10px #ececec;
                    opacity: 1;
                    border-radius: 20px;
                    padding: 10px;
                    display: flex;
                    align-items: center;
                    font-size: 12px;
                    font-family: 'Avenir', Helvetica, Arial, sans-serif;

                    span {
                        margin-left: 5px;
                    }

                    font-weight: 400;
                    color: #717882;
                    opacity: 1;
                }
            }
        }

        .btn_box {
            position: absolute;
            bottom: 10%;
            left: 50%;
            transform: translateX(-50%);

            .btn {
                width: 339px;
                height: 40px;
                background: #FF2828;
                border-radius: 6px 6px 6px 6px;
                font-family: PingFang SC, PingFang SC;
                font-weight: 400;
                font-size: 15px;
                color: #FFFFFF;
            }
        }
    }

    ::v-deep .van-cell {
        padding: 10px 0px 0px 0px;
        box-sizing: border-box;
    }

    ::v-deep .van-field__label {
        color: #333333 !important;
    }

    .pouple {
        display: flex;
        position: absolute;
        top: 4px;
        align-items: center;
        justify-content: center;

        .pouple_box {
            width: 92%;
            background-color: #fff;
            padding: 8px 12px 12px 12px;
            border-radius: 4px;
            line-height: 18px;
        }

        .pouple_font {
            margin-top: 6px;
            font-size: 14px;
        }

        .specification {
            font-size: 16px;
            font-weight: bold;
        }
    }
</style>